<!--
  @author:  long
  @date:    2023/4/4
  @file:    绩效查询
  @require:
-->
<template>
  <div class="targetAllocation">
    <div class="app-container">
      <div class="mb-3">
        <el-row :gutter="10">
          <el-col :span="3">
            <el-select
              clearable
              v-model="queryForm.targetType"
              placeholder="目标类型"
              @change="getList"
            >
              <el-option
                v-for="dict in target_type"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select
              clearable
              v-model="queryForm.targetBizSegment"
              placeholder="业务类型"
              @change="getList"
            >
              <el-option
                v-for="dict in target_biz_segment"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-date-picker
              v-model="queryForm.targetYear"
              type="year"
              style="width: 100%"
              placeholder="年度"
              value-format="YYYY"
              format="YYYY"
              @change="getList"
            />
          </el-col>
          <el-col :span="6" v-if="handleBtnShow">
            <el-input
              v-model="queryForm.assessor"
              placeholder="目标成员"
              @focus="selectAssessorUser"
              @change="getList"
            >
              <template #prepend v-if="assessorUserObj.length > 0">
                {{ assessorUserObj[0].label }}
              </template>
              <template #append>
                <el-button
                  type="primary"
                  size="small"
                  @click="selectAssessorUser"
                  >选择</el-button
                >
              </template>
            </el-input>
          </el-col>

          <el-col :span="9" style="text-align: right">
            <el-button
              v-if="handleBtnShow"
              type="primary"
              icon="plus"
              @click="addTarget"
              >目标分配</el-button
            >
            <el-button type="primary" icon="Search" @click="getList"
              >查询</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-table
        ref="targetTable"
        row-key="id"
        highlight-current-row
        v-loading="loading"
        :data="tableData"
        border
        :load="
          (row, treeNode, resolve) => {
            getRowChildren(row, treeNode, resolve, 'load')
          }
        "
        lazy
        style="width: 100%"
      >
        <el-table-column prop="memberName" label="目标对象" />
        <el-table-column align="center" label="目标财年" width="100">
          <template #default="scope"> {{ scope.row.targetYear }}年 </template>
        </el-table-column>
        <el-table-column label="业务类型" align="center" width="120">
          <template #default="scope">
            <dict-tag
              :options="target_biz_segment"
              :value="scope.row.targetBizSegment"
            />
          </template>
        </el-table-column>
        <el-table-column label="目标类型" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="target_type" :value="scope.row.targetType" />
          </template>
        </el-table-column>
        <el-table-column
          prop="targetValue"
          label="目标金额"
          align="center"
          width="120"
        >
          <template #default="scope">
            {{ scope.row.targetValue }}{{ scope.row.targetUnit }}
          </template>
        </el-table-column>
        <el-table-column
          prop="targetSeason1"
          label="第一季度"
          align="center"
          width="100"
        />
        <el-table-column
          prop="targetSeason2"
          label="第二季度"
          align="center"
          width="100"
        />
        <el-table-column
          prop="targetSeason3"
          label="第三季度"
          align="center"
          width="100"
        />
        <el-table-column
          prop="targetSeason4"
          label="第四季度"
          align="center"
          width="100"
        />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleAllocation(scope.row)"
              >分解</el-button
            >
            <el-button type="primary" link @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--  弹窗选择组件  -->
    <select-or-tree-dialog
      :dialog-param="selectOrTreeDialogParam"
      :tabsOptionsData="tabsOptionsData"
      @handleConfirm="handleConfirm"
    />
    <el-dialog
      width="70%"
      v-model="dialogVisible"
      destroy-on-close
      custom-class="targetDialog"
    >
      <template #title>
        <div class="text-2xl pl-5 font-semibold">设置业绩目标</div>
      </template>
      <add-or-update-target
        :flag="flag"
        :targetInfo="targetInfo"
        @dialogClose="dialogClose"
      ></add-or-update-target>
    </el-dialog>
  </div>
</template>

<script setup name="TargetAllocation">
import { getCurrentInstance } from 'vue'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { getUser } from '@/api/system/user'
import { format } from 'date-fns'
import { treeselect } from '@/api/rsgl/ygda'
import AddOrUpdateTarget from '@/views/salesManage/targetManage/targetAllocation/modal/addOrUpdateTarget.vue'
import {
  delSalestarget,
  getSalestargetList,
  getTargetDeatail
} from '@/api/salesManage/targetManage/targetAllocation'

const { proxy } = getCurrentInstance()
// 通用数据store
const commonStore = useCommonStore()
const userStore = useUserStore()

const handleBtnShow = ref(false)
const loading = ref(false)

const data = reactive({
  queryForm: {
    targetYear: ''
  },
  leadersDeptOptions: [],
  companyOptions: [],
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {}, // select
  userInfo: {}, //用户信息
  tableData: []
})
const { queryForm, companyOptions, dialogParam, selectOptionObj, tableData } =
  toRefs(data)
// 弹窗开关
const dialogVisible = ref(false)
// 考核人对象数组
const assessorUserObj = ref([])
const tabsOptionsData = ref([])
const selectOrTreeDialogParam = ref({})
const targetInfo = ref('')
const flag = ref('add')
const targetRow = ref({})
const tableTreeRefreshTool = new Map()

const { target_type, target_biz_segment } = proxy.useDict(
  'target_type',
  'target_biz_segment'
)

/**
 * 分配
 */
const handleAllocation = row => {
  console.info('proxy.$refs.targetTable.store', proxy.$refs.targetTable.store)
  if (proxy.$refs.targetTable.store.states.treeData.value[row.id]) {
    proxy.$refs.targetTable.store.states.treeData.value[row.id].loaded = false
  }
  // 当前选中的行数据
  targetRow.value = row
  let params = {
    id: row.id
  }
  getTargetDeatail(params).then(res => {
    targetInfo.value = res.data
    proxy.$nextTick(() => {
      flag.value = 'update'

      dialogVisible.value = true
    })
  })
}

/**
 * 删除目标
 */
const handleDel = row => {
  proxy
    .$confirm('是否确认删除?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      let params = {
        ids: row.id
      }
      delSalestarget(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        getList()
      })
    })
}

/**
 * 树结构懒加载
 * @param row
 */
const getRowChildren = (row, treeNode, resolve, type) => {
  let params = {
    ...queryForm.value,
    parentId: row.id
  }

  getSalestargetList(params).then(res => {
    if (res.data != null && res.data.length > 0) {
      row.hasChildren = true
      res.data.forEach(item => {
        if (item.sonNum > 0) {
          item.hasChildren = true
        }
      })
      console.info('row', row)
      tableTreeRefreshTool.set(row.id, { row, treeNode, resolve })
      if (resolve) {
        resolve(res.data)
      }
    }
  })
}

/**
 * 添加目标
 */
const addTarget = () => {
  targetRow.value = {}
  flag.value = 'add'
  dialogVisible.value = true
}

/**
 * dialogClose 关闭弹窗，并且设置flag为false
 */
const dialogClose = async flag => {
  dialogVisible.value = false
  targetInfo.value = ''
  console.info('proxy.$refs.targetTable', proxy.$refs.targetTable)
  proxy.$refs.targetTable.store.loadOrToggle(targetRow.value)
  if (tableTreeRefreshTool.get(targetRow.value.id) != undefined) {
    const { row, treeNode, resolve } = tableTreeRefreshTool.get(
      targetRow.value.id
    )
    getRowChildren(row, treeNode, resolve)
  } else {
    if (flag == 'add') {
      getList()
    } else {
      getRowChildren(targetRow.value)
    }
  }
}

/**
 * @description: 选择考核人
 */
const selectAssessorUser = () => {
  //   tabs配置数组
  tabsOptionsData.value = [
    {
      label: '单位', //tab的label
      name: 'org', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'org', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'deptId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'deptName', //树节点的label
        apiParams: {
          deptId: userStore.user.orgId != '484' ? userStore.user.orgId : ''
        }
      }
    },
    {
      label: '部门', //tab的label
      name: 'dept', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'dept', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'deptId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'deptName', //树节点的label
        apiParams: {
          deptId: userStore.user.orgId != '484' ? userStore.user.orgId : ''
        }
      }
    },
    {
      label: '人员列表', //tab的label
      name: 'person', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'person', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'uuid', //节点的key
        defaultCheckedKeys: [] //默认选中的节点
      }
    }
  ]
  // 如果考核人对象数组有值
  if (assessorUserObj.value.length > 0) {
    //assessorUserObj,用find查找tabsOptionsData中name等于assessorUserObj的name的对象
    //将对象的componentOptions.defaultCheckedKeys设置为考核人对象数组中的selectData的itemValue集合
    //componentOptions的selectData等于assessorUserObj中的selectData
    assessorUserObj.value.forEach(item => {
      const obj = tabsOptionsData.value.find(tab => tab.name === item.name)
      obj.componentOptions.defaultCheckedKeys = item.selectData.map(
        item => item.itemValue
      )
      obj.componentOptions.selectData = item.selectData
    })
  }

  proxy.$nextTick(() => {
    // 弹窗标题
    selectOrTreeDialogParam.value.title = '请选择目标成员'
    // 弹窗是否发开
    selectOrTreeDialogParam.value.isDialog = true
    //  是否多选，如果结果要为单选，则组件componentOptions.multiple设置为false
    selectOrTreeDialogParam.value.resultMultiple = false
  })
}

/**
 * 考核人弹窗确定按钮
 */
const handleConfirm = result => {
  console.info('result', result)
  if (result.length > 0) {
    queryForm.value.assessor = result[0].selectData[0].itemLabel
    // 设置考核人对象数组
    assessorUserObj.value = result
  } else {
    queryForm.value.assessor = ''
    // 设置考核人对象数组
    assessorUserObj.value = []
  }
}

/**
 * 初始化用户信息
 * @param userId
 * @returns {Promise<void>}
 */
const initUserInfo = async uid => {
  console.info(userStore.user)

  // 销售目标管理员
  if (userStore.user.roles.findIndex(item => item.roleKey == 'xsmbgly') != -1) {
    handleBtnShow.value = true
  }

  // 根据id获取用户信息
  // getUser(userId).then(res => {
  //   userInfo.value = res.data
  //   getAssessViewListByUserId()
  // })
  //   获取当前用户分管部门数据
}

const getList = () => {
  tableData.value = []
  loading.value = true
  let params = {
    ...queryForm.value
  }
  if (assessorUserObj.value.length > 0) {
    console.info(assessorUserObj.value)
    params.memberId = assessorUserObj.value[0].selectData[0].itemValue

    switch (assessorUserObj.value[0].name) {
      case 'org':
        params.memberType = '1'
        break
      case 'dept':
        params.memberType = '2'

        break
      case 'person':
        params.memberType = '3'
        break
    }
  }
  // else {
  //   params.memberId = userStore.user.userId
  //   params.memberType = '3'
  // }
  getSalestargetList(params)
    .then(res => {
      let arr = proxy.handleTree(res.data)
      arr.forEach(item => {
        if (item.sonNum != null && item.sonNum != 0) {
          item.hasChildren = true
        }
        if (item.children && item.children.length) {
          item.children.forEach(t => {
            t.hasChildren = true
          })
        }
      })
      console.info('arr', arr)
      tableData.value = arr
      console.info('tableData', tableData.value)
    })
    .finally(res => {
      loading.value = false
    })
}

/**
 * 初始化查询
 */
const init = () => {
  //初始化用户信息
  initUserInfo(userStore.user.userId)
  getList()
}
init()
</script>

<style scoped lang="scss">
.i-ion-ios-paper {
  color: var(--el-color-primary);
}
.tab-item {
  @apply text-gray-500 px-10 py-2 cursor-pointer text-lg mx-2;
}
.isActive {
  @apply rounded-full border-1 border-blue-500 border-solid text-blue-500;
}

:deep(.monthPopper) {
  width: 300px !important;
}
.monthPopper .el-select-dropdown__item {
  width: 25%;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  padding: 0;
}

:deep(.targetDialog) {
  border-radius: 10px;
  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__header {
    @apply py-5 mr-0 border-b-1 border-b-solid border-gray-200;
  }
  .el-dialog__headerbtn {
    top: 0;
  }
}
</style>
